package com.simon.seckill.mq.handler;

import com.simon.seckill.Exceptions.SeckillExceptions;
import com.simon.seckill.cache.GoodsRedisStoreCache;
import com.simon.seckill.cache.SeckillFinishCache;
import com.simon.seckill.cache.SeckillSuccessTokenCache;
import com.simon.seckill.cache.UserBlackListCache;
import com.simon.seckill.constant.CommonConstant;
import com.simon.seckill.mq.message.SeckillRequestMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wang.moshu.message.AbstarctMessageHandler;

/**
 *
 *
 * */
@Service
public class SeckillRequestHandler extends AbstarctMessageHandler<SeckillRequestMessage> {

    private static Log logger = LogFactory.getLog(SeckillRequestHandler.class);

    @Autowired
    private UserBlackListCache userBlackListCache;

    @Autowired
    private SeckillFinishCache seckillFinishCache;

    @Autowired
    private GoodsRedisStoreCache goodsRedisStoreCache;

    @Autowired
    private SeckillSuccessTokenCache seckillSuccessTokenCache;

    public SeckillRequestHandler() {
        super(CommonConstant.MessageType.SECKILL_MESSAGE, SeckillRequestMessage.class, Integer.MAX_VALUE);
    }

    @Override
    public void handle(SeckillRequestMessage message) {
        // 查看请求用户是否在黑名单中
        if (userBlackListCache.isIn(message.getPhone())) {
            logger.error(message.getPhone()+ "检测为黑名单，拒绝抢购");
            return;
        }
        // 先看抢购是否结束了
        if (seckillFinishCache.isFinish(message.getGoodRandomName())) {
            logger.error("不要意思，您来晚了！");
            return;
        }

        // 先减redis库存
        if (!goodsRedisStoreCache.decreaseStore(message.getGoodRandomName())) {
            throw new SeckillExceptions("占redis名额失败，等待重试");
        }

        // 减库成功生成下单token，并存入redis供前端获取
        String token = seckillSuccessTokenCache.getToken(message.getPhone(), message.getGoodRandomName());
        logger.error("占位成功！下单token为:"+token);
    }

    @Override
    public void handleFailed(SeckillRequestMessage message) {

    }
}
